<template>
  <div class="search">
    <div class="rentType">
      <div class="select">
        <el-select v-model="form.city" class="block" placeholder="请选择城市" @change="handleCityChange">
          <el-option label="成都市" value="成都市"></el-option>
          <el-option label="北京市" value="北京市"></el-option>
          <el-option label="上海市" value="上海市"></el-option>
          <el-option label="杭州市" value="杭州市"></el-option>
          <el-option label="重庆市" value="重庆市"></el-option>
          <el-option label="广州市" value="广州市"></el-option>
        </el-select>

        <el-select v-model="form.area" class="block" filterable placeholder="请选择区域">
          <el-option
              v-for="(item,index) in communityOptions"
              :key="index"
              :label="item"
              :value="item"
          >
          </el-option>

        </el-select>
        <el-select v-model="form.rentType" class="block" placeholder="请选择类型">
          <el-option label="整租" value="整租"></el-option>
          <el-option label="合租" value="合租"></el-option>
        </el-select>

        <div class="block">
          <span>选择价格范围</span>
          <el-slider v-model="form.price" :marks="marks1" :max="10000" class="block2" range></el-slider>
          <span>选择面积范围</span>
          <el-slider v-model="form.capacity" :marks="marks2" :max="200" class="block2" range></el-slider>
        </div>
        <el-button style="width: 300px;" type="primary" @click="searchHouse">搜索</el-button>
      </div>
      <div class="houses">
        <div v-for="item in list" :key="item.id" :class="{'three-per-row': pageSize === 6, 'two-per-row': pageSize === 4}" class="tab" >
          <houseItem :item="item" />
        </div>
        <div class="Page">
          <el-pagination :current-page.sync="pageNum"
                         :page-size="pageSize"
                         :page-sizes="[4, 6]"
                         :total="allList.length"
                         layout="total, sizes, prev, pager, next"
                         @current-change="handlePage"
                         @size-change="handleSizeChange"
          >
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import houseItem from '@/components/houseItem.vue'
import axios from "axios";

export default {
  name: 'RentType',
  components: {
    houseItem
  },
  created() {
    this.handlePage(1)
    //确保第一次从nav进入只请求一次
    if (!this.$route.query.nav) {
      this.getHouseInfo1()
    }
  },

  data() {
    return {
      //搜索条件
      communityOptions: [], // 区域选项
      communityMap: {
        '成都市': ['温江区', '郫都区', '新都区', '双流区', '武侯区'],
        '北京市': ['朝阳区', '海淀区', '西城区', '东城区'],
        '上海市': ['浦东新区', '静安区', '黄浦区'],
        '杭州市': ['西湖区', '上城区', '下城区'],
        '重庆市': ['渝中区', '江北区', '沙坪坝区', '九龙坡区'],
        '广州市': ['天河区'],
      },
      form: {
        city: '',
        area:'',
        rentType: '',
        name: '',
        price: [0, 5000],
        capacity: [0, 100],
      },
      //标记
      marks1: {
        0: '0',
        2500: '2500',
        5000: '5000',
        7500: '7500',
        10000: '10000',
      },
      marks2: {
        0: '0',
        50: '50',
        100: '100',
        150: '150',
        200: '200',

      },
      //当前页
      pageNum: 1,
      pageSize: 4,
      //请求参数
      msg: {
        title: '',
        city: '',
        area:'',
        rentType: '',
        minPrice: '0',
        maxPrice: '999999',
        minCapacity: '0',
        maxCapacity: '999'
      },
      filteredList:[],
      list: [],
      allList:[],
    }
  },
  //监听路由重新发起请求
  watch: {
    // 监听路由变化
    '$route'(to, from) {
      if (to.query.type !== from.query.type) {
        this.getHouseInfo1() // 重新获取数据
        //this.searchHouse()
      }
    },
  },

  /*watch: {
    '$route': {
      handler(newRoute) {
        // 判断是否是刷新或参数变化
        if (newRoute.name === 'RentType') {
          this.searchHouse(); // 重新发起请求
        }
      },
      deep: true,
      immediate: true
    }
  },*/

  methods: {
    //城市和区域联动
    handleCityChange(city) {
      this.form.area = '';//清空区域内容
      this.communityOptions = this.communityMap[city] || []
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.handlePage(1,size)
    },

    //分页
    handlePage(page) {
      const start = (page - 1) * this.pageSize;
      const end = page * this.pageSize;
      this.list = this.allList.slice(start, end);
    },

    //初始化房子信息
    getHouseInfo() {
      this.msg.city = this.$route.query.city || '',
      this.msg.area = this.$route.query.area || '',
      this.msg.rentType = this.$route.query.type || '',
      this.msg.maxPrice = this.$route.query.monthRent || '999999',
      axios({
        url: 'http://localhost:8090/house/listAll',
        method: 'get',
      }).then(res => {
        if (res.code === '200') {
          this.allList = res.data
          this.handlePage(1)

        } else {
          this.$message.error(res.msg)
        }
      })
    },

    //初始化房屋信息：首页进行模糊查询返回结果
    getHouseInfo1() {
          axios({
            url: 'http://localhost:8090/house/search',
            method: 'post',
            data: {
              city : this.$route.query.city || '',
              area : this.$route.query.area || '',
              rentType : this.$route.query.type || '',
              maxPrice : this.$route.query.monthRent || '999999',
            }
          }).then(res => {
            if (res.code === '200') {
              this.allList = res.data
              this.list = this.allList.map(item => {
                if (typeof item.imgUrl === 'string') {
                  try {
                    item.imgUrl = JSON.parse(item.imgUrl); // 解析为数组
                  } catch (e) {
                    item.imgUrl = [item.imgUrl]; // 如果解析失败，转为单元素数组
                  }
                }
                return item;
              }).slice(0, 4);
            } else {
              this.$message.error(res.msg)
            }
          })
    },

    //测试
    /*searchHouse2() {
      this.getHouseInfo2()
    },*/

    //测试
    /*getHouseInfo2() {
      axios({
        url: 'http://localhost:8090/house/search',
        method: 'post',
        data: {
          city : this.form.city?this.form.city:this.$route.query.city ,
          area : this.form.area?this.form.area:this.$route.query.area,
          rentType : this.form.rentType?this.form.rentType:this.$route.query.type,
          maxPrice : this.form.price?this.form.price[1]:this.$route.query.monthRent,
        }
      }).then(res => {
        if (res.code === '200') {
          this.allList = res.data
          this.list = this.allList.map(item => {
            if (typeof item.imgUrl === 'string') {
              try {
                item.imgUrl = JSON.parse(item.imgUrl); // 解析为数组
              } catch (e) {
                item.imgUrl = [item.imgUrl]; // 如果解析失败，转为单元素数组
              }
            }
            return item;
          }).slice(0, 4);
        } else {
          this.$message.error(res.msg)
        }
      })
    },*/

    //搜索
    searchHouse() {
      axios({
        url: 'http://localhost:8090/house/search2',
        method: 'post',
        data: {
          //city: this.form.city,
          //city:this.$route.query.city?this.$route.query.city:this.form.city,
          city:this.form.city?this.form.city:this.$route.query.city,
          area: this.form.area,
          rentType: this.form.rentType || '',
          minPrice: this.form.price[0],
          maxPrice: this.form.price[1],
          minCapacity: this.form.capacity[0],
          maxCapacity: this.form.capacity[1],
        }
      }).then(res => {
        if (res.code === '200') {
          this.allList = res.data
          this.list = this.allList.map(item => {
            if (typeof item.imgUrl === 'string') {
              try {
                item.imgUrl = JSON.parse(item.imgUrl); // 解析为数组
              } catch (e) {
                item.imgUrl = [item.imgUrl]; // 如果解析失败，转为单元素数组
              }
            }
            return item;
          }).slice(0, 4);
        } else {
          this.$message.warning(res.msg)
          this.list = []
          this.allList = []
        }
      })
    }
  },
}
</script>

<style scoped>
.search {
  background-color: #f8f9fe;
  min-width: 1100px;
  min-height: 821px;
  padding: 50px 240px;
}

.rentType {
  display: flex;
  justify-content: space-evenly;
  padding-left: 5px;
}

.select {
  width: 330px;
  height: 450px;
  padding: 30px 20px;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: center;

}

.block {
  width: 300px;
  margin-bottom: 10px;
  margin-top: 10px;
  font-weight: 600;
}

.block2 {
  width: 320px;
  margin-bottom: 30px;
  transform: translateX(-10px);
}

.houses {
  width: 700px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0 20px;
}

.tab>* {
  margin-bottom: 20px;
}

.Page {
  display: flex;
  justify-content: center;
  margin-bottom:  10px;
  padding: 2px 150px;
}


</style>